package com.easygoods.tasks;

import com.bestvike.stone.core.collection.CollectionUtils;
import com.bestvike.stone.spring.page.PageableRequest;
import com.easygoods.dao.MemberInfoDao;
import com.easygoods.service.CouponService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@CommonsLog
public class CouponExpiredScheduling {
    private static final int PAGE_SIZE = 50;
    @Autowired
    private CouponService couponService;
    @Autowired
    private MemberInfoDao memberInfoDao;


    //每天 0 点执行  秒 分 时 日 月 周
    @Scheduled(cron = "0 0 1 * * ?")
    public void expirePoints() {
        log.info("=======开始批量代金券过期");
        PageableRequest request = new PageableRequest();
        request.setPageSize(PAGE_SIZE);
        request.setPageNum(1);
        List<String> memberIdList = this.memberInfoDao.getMemberIdList(request.toRowBounds());
        while (!memberIdList.isEmpty()) {
            for (String memberId : memberIdList) {
                List<String> couponIdList = this.couponService.getExpiredCouponList(memberId);
                if (CollectionUtils.isEmpty(couponIdList)) {
                    log.info("该用户无过期的代金券,memberId:" + memberId);
                    continue;
                }
                for (String couponId : couponIdList) {
                    try {
                        log.info("======开始过期代金券,memberId:" + memberId + " couponId:" + couponId);
                        this.couponService.expireCoupon(memberId, couponId);
                        log.info("======过期该代金券成功,memberId:" + memberId + " couponId:" + couponId);
                    } catch (Exception e) {
                        log.error("过期代金券失败,memberId:" + memberId + "couponId:" + couponId);
                    }
                }
            }
            request.setPageNum(request.getPageNum() + 1);
            memberIdList = this.memberInfoDao.getMemberIdList(request.toRowBounds());
        }
        log.info("=======批量代金券过期完成");
    }
}
